import { NavigationGuardWithThis, NavigationHookAfter } from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { useSystemStore } from "@/store/system";
import { isEmpty } from "lodash-es";

NProgress.configure({ showSpinner: false });

// 开启进度条
const NProgressStart: NavigationGuardWithThis<undefined> = (to, from, next) => {
  NProgress.start();
  next();
};

// 登录和菜单权限
const authGuard: NavigationGuardWithThis<undefined> = (to, from, next) => {
  const name = to.name as string;
  if (["login","/signIn", "404", "403"].includes(name)) {
    next();
    return;
  }

  const systemStore = useSystemStore();
  // 检验是否存在用户信息
  if (isEmpty(systemStore.userInfo)) {
    next("/logon");
    return;
  }

  // 是否已经整理本地name的集合
  if (!systemStore.locRouteNames.length) {
    systemStore.setLocRouteNames();
  }

  // 判断目标页面是否有权限
  const { locRouteNames, menuRouteNames } = systemStore;
  if (!locRouteNames.includes(name)) {
    // next('/404')
    next(); //  后期需要改回上行代码
  } else if (!menuRouteNames.includes(name)) {
    next("/403");
  } else {
    next();
  }
};

const afterEach1: NavigationHookAfter = (to) => {
  NProgress.done();
};

const guards = {
  beforeEach: [NProgressStart, authGuard],
  afterEach: [afterEach1],
};

export default guards;
